package com.cat.dataStructure02;

import java.util.Arrays;
import java.util.PriorityQueue;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/minimum-array-sum/
 * @create 2025/10/14 15:43
 * @since JDK17
 */

public class Solution18 {
    public int minArraySum(int[] nums, int k, int op1, int op2) {
        int n = nums.length, ans = Arrays.stream(nums).sum();
        PriorityQueue<int[]> heap = new PriorityQueue<>((a, b) -> b[0] - a[0]);
        for (int num : nums) {
            heap.add(new int[]{num, 0, 0});
        }
        while (op1 != 0 || op2 != 0) {
            var x = heap.poll();
            int p1 = (x[1] == 0 ? x[0] / 2 : 0), p2 = (x[2] == 0 && x[0] >= k ? k : 0);
            if (p1 > p2) {
                ans -= p1;
                x[0] -= p1;
                x[1] = 1;
                if (x[2] == 0) {
                    heap.add(x);
                }
                op1--;
            } else {
                ans -= p2;
                x[0] -= p2;
                x[2] = 1;
                if (x[1] == 0) {
                    heap.add(x);
                }
                op2--;
            }
        }

        return ans;
    }
}
